class MagicDictionary:

    def __init__(self):
        self.length_to_words = {}

    def buildDict(self, dictionary):
        """构建字典，按单词长度分组存储"""
        for word in dictionary:
            length = len(word)
            if length not in self.length_to_words:
                self.length_to_words[length] = []
            self.length_to_words[length].append(word)

    def search(self, searchWord):
        """搜索是否存在只差一个字符的单词"""
        length = len(searchWord)
        if length not in self.length_to_words:
            return False

        for candidate in self.length_to_words[length]:
            diff_count = 0
            for c1, c2 in zip(candidate, searchWord):
                if c1 != c2:
                    diff_count += 1
                    if diff_count > 1:  # 贪心剪枝：超过1个差异立即停止
                        break
            if diff_count == 1:
                return True
        return False
